//
//  ExchangeRateCulVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/12/22.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "ExchangeRateCulVC.h"
#import "ExchgeRateCulTowCell.h"
#import "ExchgeRateCulTopCell.h"
#import "SelectCurrencyVC.h"

#import "BaseNavigationController.h"

#import "SelectedListView.h"
#import "ExchangRateModel.h"
#import <LEEAlert/LEEAlert.h>

#import "HuiLVBottomView.h"
@interface ExchangeRateCulVC ()


@property (nonatomic, strong) HuiLVBottomView *footerView;


@property (nonatomic, strong) ExchangRateModel *model;


/** <#note#> */
@property (nonatomic, weak) UILabel *bottmLabel;

@end

@implementation ExchangeRateCulVC

- (UILabel *)bottmLabel{
    if (!_bottmLabel) {
        UILabel *label = [[UILabel alloc]init];
        
        label.font = MYFONT(13);
        
        label.textColor = themeColor;
        
        label.text = @"声明: 菲度汇率仅供参考,最终以各银行实际交易汇率为准。";
        
        NSMutableDictionary *tempDic = [[NSMutableDictionary alloc]init];
        tempDic[NSFontAttributeName] = MYFONT(13);
        
        CGSize size = [label.text boundingRectWithSize:CGSizeMake(KScreenW - 40, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:tempDic context:nil].size;
        
         CGFloat tempMargin = IPhoneX ? 44 : 10;
        label.frame = CGRectMake(20, KScreenH - size.height - tempMargin, KScreenW - 40, size.height);
        
        _bottmLabel = label;
        
        
        [self.view addSubview:_bottmLabel];
        
    }
    
    
    
    return _bottmLabel;
}

- (ExchangRateModel *)model{
    
    if (!_model) {
        
        _model = [[ExchangRateModel alloc]init];
        
        _model.topImageName = @"PHP";
        
        _model.bottomImageName = @"CNY";

    }
    
    
    return _model;
}


- (HuiLVBottomView *)footerView{
    
    if (!_footerView) {
        
        HuiLVBottomView *temp = (HuiLVBottomView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([HuiLVBottomView class]) owner:nil options:nil].firstObject;
        
        temp.backgroundColor = viewBgGrey;
        
        [temp.rihtBtn addTarget:self action:@selector(calculationBtnDidTap) forControlEvents:UIControlEventTouchUpInside];
        
        [temp.leftBtn addTarget:self action:@selector(exchageImage) forControlEvents:UIControlEventTouchUpInside];
        
        _footerView = temp;
        
        CGFloat tempH = IPhoneX ? 88 : 64;
        
        _footerView.height = KScreenH - 122 - tempH;
        
        
    }
    
    return _footerView;
}


- (void)exchageImage{
    
    NSString *temp = self.model.bottomImageName;
    
    self.model.bottomImageName = self.model.topImageName;
    
    self.model.topImageName = temp;
    
    if (self.model.name.length > 0) {
        
        [self.plainTableView reloadData];
        
        [self calculationBtnDidTap];
        
    } else {
        
        self.model.exchangeRate = nil;
        
        [self.plainTableView reloadData];
    }
    
}



- (void)calculationBtnDidTap{
    
    [self.view endEditing:YES];
    
    if (self.model.name == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"输入计算金额"];
        
        return;
    }
    
    
    
    //判断是否是纯数字
    
    if( [self isPureInt:self.model.name] || [self isPureFloat:self.model.name])
        
    {
        
        
        if (!(self.model.name.floatValue > 0)) {
            
            [SVProgressHUD showInfoWithStatus:@"输入金额非法"];
            
            return;
        }
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        
        parameters[@"num"] = self.model.name;
        
        parameters[@"from"] = self.model.topImageName;
        
        parameters[@"to"] = self.model.bottomImageName;

        
        [SVProgressHUD showWithStatus:@"正在计算中..."];
        
        MJWeakSelf;
        [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Rate/changeMoney" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
            
            [SVProgressHUD dismiss];
            MYJSONSTR
//
//            NSLog(@"%@",error);
            
            if (!error) {
                
                weakSelf.model.exchangeRate = responseObject[@"data"][@"money"];
                
                
                [weakSelf.plainTableView reloadData];
                
            } else {
                
                [SVProgressHUD showInfoWithStatus:error.domain];

                
            }
        }];
        
        
       
        
    }else{
        
      
        [SVProgressHUD showInfoWithStatus:@"输入金额非法"];
        
        
  
        
        
    }
    

    
}






//判断是否为整形：

- (BOOL)isPureInt:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    int val;
    
    return [scan scanInt:&val] && [scan isAtEnd];
    
}


//判断是否为浮点形：

- (BOOL)isPureFloat:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    float val;
    
    return [scan scanFloat:&val] && [scan isAtEnd];
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"汇率计算";
    
//    [UIPasteboard generalPasteboard].string
    
    self.plainTableView.backgroundColor = viewBgGrey;
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ExchgeRateCulTopCell class]) bundle:nil] forCellReuseIdentifier:[ExchgeRateCulTopCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ExchgeRateCulTowCell class]) bundle:nil] forCellReuseIdentifier:[ExchgeRateCulTowCell identifierStr]];
    
    self.plainTableView.tableFooterView = self.footerView;
    
    
    self.bottmLabel.backgroundColor = viewBgGrey;
    
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startCalculate) name:@"StartCalculate" object:nil];
}

- (void)startCalculate{
    
    if (self.model.name == nil) {
        
        
        return;
    }
    
    
    
    //判断是否是纯数字
    
    if( [self isPureInt:self.model.name] || [self isPureFloat:self.model.name])
        
    {
        
        
        if (!(self.model.name.floatValue > 0)) {
            
            [SVProgressHUD showInfoWithStatus:@"输入金额非法"];
            
            return;
        }
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        
        parameters[@"num"] = self.model.name;
        
        parameters[@"from"] = self.model.topImageName;
        
        parameters[@"to"] = self.model.bottomImageName;
        
        
        [SVProgressHUD showWithStatus:@"正在计算中..."];
        
        MJWeakSelf;
        [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Rate/changeMoney" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
            
            [SVProgressHUD dismiss];
            MYJSONSTR
            //
            //            NSLog(@"%@",error);
            
            if (!error) {
                
                weakSelf.model.exchangeRate = responseObject[@"data"][@"money"];
                
                
                [weakSelf.plainTableView reloadData];
                
            } else {
                
                [SVProgressHUD showInfoWithStatus:error.domain];
                
                
            }
        }];
        
        
        
        
    }else{
        
        
        [SVProgressHUD showInfoWithStatus:@"输入金额非法"];
        
        
        
        
        
    }
    
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];

}

#pragma mark - tableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        ExchgeRateCulTopCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ExchgeRateCulTopCell identifierStr]];
        
        tableCell.model = self.model;

        return tableCell;
        
        
    } else {
        
        if (indexPath.row == 1) {
            
            ExchgeRateCulTowCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ExchgeRateCulTowCell identifierStr]];
            
            tableCell.model = self.model;
            
            return tableCell;
        } else {
            return [[UITableViewCell alloc]init];
        }

    }
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        return 60;

    } else {
        if (indexPath.row == 1) {
            return 72;

        } else {
            return 0;

        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
    
    if (indexPath.row == 0) {
        [self selectType1];
    }else{
        
       [self selectType];
        
    }
    
//    SelectCurrencyVC *temp = [[SelectCurrencyVC alloc]init];
//
//    BaseNavigationController *nav = [[BaseNavigationController alloc]initWithRootViewController:temp];
//
//    nav.modalTransitionStyle  = UIModalTransitionStyleFlipHorizontal;
//
////    nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
//
//    [self presentViewController:nav animated:YES completion:nil];
    
    
    
    
    
}



- (void)selectType{
    
    SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, 280, 0) style:UITableViewStylePlain];
    
    view.isSingle = YES;
    
   
    
    NSMutableArray *strArray = [NSMutableArray array];
    
    if (![self.model.topImageName isEqualToString:@"CNY"]) {
        [strArray addObject:@"CNY"];
    }
    
    if (![self.model.topImageName isEqualToString:@"USD"]) {
        [strArray addObject:@"USD"];
        
    }
    
    if (![self.model.topImageName isEqualToString:@"JPY"]) {
        [strArray addObject:@"JPY"];
        
    }
    
    if (![self.model.topImageName isEqualToString:@"HKD"]) {
        [strArray addObject:@"HKD"];
        
    }
    
    if (![self.model.topImageName isEqualToString:@"EUR"]) {
        [strArray addObject:@"EUR"];
        
    }
    
    
    if (![self.model.topImageName isEqualToString:@"PHP"]) {
        [strArray addObject:@"PHP"];
        
    }
    
    
    if (![self.model.topImageName isEqualToString:@"GBP"]) {
        [strArray addObject:@"GBP"];
        
    }
    
    
    
    NSMutableArray *selectedListArray = [NSMutableArray array];
    
    for (int i = 0; i < strArray.count; i++) {
        
        NSString *lastTemp = strArray[i];
        
        [selectedListArray addObject:[[SelectedListModel alloc] initWithSid:0 Title:lastTemp]];
    }
    
    
    view.array = selectedListArray;
    
    MJWeakSelf;
    view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
        
        [LEEAlert closeWithCompletionBlock:^{
            
            weakSelf.model.bottomImageName = [array firstObject].title;
            
            
            if (weakSelf.model.name.length > 0) {
                [weakSelf.plainTableView reloadData];

                [weakSelf calculationBtnDidTap];
                
            } else {
                
                weakSelf.model.exchangeRate = nil;
                
                [weakSelf.plainTableView reloadData];
            }
            
            
            
        }];
        
    };
    
    [LEEAlert alert].config
    .LeeTitle(@"币种选择")
    .LeeItemInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeCustomView(view)
    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
    .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeClickBackgroundClose(YES)
    .LeeShow();
    
    
    
}






- (void)selectType1{
    
    SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, 280, 0) style:UITableViewStylePlain];
    
    view.isSingle = YES;
    
    NSMutableArray *strArray = [NSMutableArray array];
    
    if (![self.model.bottomImageName isEqualToString:@"CNY"]) {
        [strArray addObject:@"CNY"];
    }
    
    if (![self.model.bottomImageName isEqualToString:@"USD"]) {
        [strArray addObject:@"USD"];

    }
    
    if (![self.model.bottomImageName isEqualToString:@"JPY"]) {
        [strArray addObject:@"JPY"];

    }
    
    if (![self.model.bottomImageName isEqualToString:@"HKD"]) {
        [strArray addObject:@"HKD"];

    }
    
    if (![self.model.bottomImageName isEqualToString:@"EUR"]) {
        [strArray addObject:@"EUR"];

    }
    
    
    if (![self.model.bottomImageName isEqualToString:@"PHP"]) {
        [strArray addObject:@"PHP"];

    }
    
    
    if (![self.model.bottomImageName isEqualToString:@"GBP"]) {
        [strArray addObject:@"GBP"];

    }
    
    
    
    NSMutableArray *selectedListArray = [NSMutableArray array];

    for (int i = 0; i < strArray.count; i++) {
        
        NSString *lastTemp = strArray[i];
        
        [selectedListArray addObject:[[SelectedListModel alloc] initWithSid:0 Title:lastTemp]];
    }
    

    view.array = selectedListArray;
    
    MJWeakSelf;
    view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
        
        [LEEAlert closeWithCompletionBlock:^{
            
            weakSelf.model.topImageName = [array firstObject].title;
            
            
            if (weakSelf.model.name.length > 0) {
                
                [weakSelf calculationBtnDidTap];
                [weakSelf.plainTableView reloadData];

            } else {
                
                weakSelf.model.exchangeRate = nil;
                
                [weakSelf.plainTableView reloadData];
            }
            
         
            
        }];
        
    };
    
    [LEEAlert alert].config
    .LeeTitle(@"币种选择")
    .LeeItemInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeCustomView(view)
    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
    .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeClickBackgroundClose(YES)
    .LeeShow();
    
    
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self.view endEditing:YES];
    [self startCalculate];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
